package com.zywl.api;

import com.zywl.core.beans.PayRecord;
import com.zywl.core.beans.Setmeal;
import com.zywl.service.PayRecordService;
import com.zywl.service.SetmealService;
import com.zywl.utils.models.JsonResult;
import com.zywl.web.controller.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api/payrecord/")
public class PayRecordApi extends BaseController {
    @Autowired
    private PayRecordService payRecordService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 创建支付订单
     */

    @ResponseBody
    @RequestMapping("create")
    public JsonResult create(PayRecord form){
        JsonResult jr = new JsonResult();
        Date date = new Date();
        try {
            if (form.getPrdAssId() == null){
                return jr.error("协会id不能为空");
            }
            if (form.getPrdCompanyId() == null){
                return jr.error("公司id不能为空");
            }
            if (form.getPrdMemberId() == null){
                return jr.error("购买人id不能为空");
            }
            if (form.getPrdSetmealId() == null){
                return jr.error("套餐id不能为空");
            }
            Setmeal setmeal = setmealService.getById(form.getPrdSetmealId());
            if(setmeal == null){
                return jr.error("该套餐不存在，请选择其他套餐");
            }
            form.setPrdSetmealName(setmeal.getSemName());
            form.setPrdSetmealTime(setmeal.getSemNum() + setmeal.getSemUnit());
            form.setPrdMoney(setmeal.getSemMoney());
            form.setPrdPayTime(date);
            form.setPrdIspay("0");
            form.setPrdIsuse("0");
            form.setPrdStt("0");
            form.setPrdCreateTime(date);
            form.setPrdModifyTime(date);
            payRecordService.save(form);
            jr.success("创建成功",form.getPrdId());
        }catch (Exception e){
            logger.error("创建支付订单失败",e);
        }
        return jr;
    }

    /**
     * 用户支付成功修改订单状态
     */
    @ResponseBody
    @RequestMapping("modifyispay")
    public JsonResult modifyispay(Long prdId){
        JsonResult jr = new JsonResult();
        try {
            if(prdId == null){
                return jr.error("支付订单id不能为空");
            }
            jr = payRecordService.modifyIsPay(prdId);
        }catch (Exception e){
            logger.error("修改支付状态失败",e);
            jr.error("修改支付状态失败");
        }
        return jr;
    }

}
